/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.emergency.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.util.DocConverterUtils;
import com.koron.common.web.Util;
import com.koron.emergency.bean.MaterialCheckResultView;
import com.koron.emergency.domain.EmergencyMaterial;
import com.koron.emergency.mapper.EmergencyMaterialMapper;
import com.koron.emergency.service.api.EmergencyMaterialService;
import com.koron.emergency.util.BusinessCode;
import com.koron.risk.bean.CorpBean;
import com.koron.risk.mapper.CorpManagementMapper;
import com.koron.system.domain.DictData;
import com.koron.system.mapper.DictDataMapper;
import com.koron.system.service.api.DictDataService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class EmergencyMaterialServiceImpl implements EmergencyMaterialService {

    private final static  Logger logger = LoggerFactory.getLogger(EmergencyMaterialServiceImpl.class);

    @Autowired
    private FastDFSClientWrapper clientWrapper;

    @Autowired
    private DocConverterUtils docConverterUtils;

    @Autowired
    private DictDataService dataService;

    @Autowired
    private Util util;

    @Override
    public MessageBean<Integer> save(EmergencyMaterial bean, String keepFiles, String delFiles, String pdfKeepFiles, String pdfDelFiles, MultipartFile[] files) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "保存成功", Integer.class);
        List<String> keepList = new ArrayList<>();
        List<String> keepPdfList = new ArrayList<>();
        SessionFactory factory = new SessionFactory();
        try {
            if (StringUtils.isEmpty(bean.getName())) {
                msg.setCode(BusinessCode.EMERGENCYMATERIAL_EMPTY_NAME.getCode());
                msg.setDescription(BusinessCode.EMERGENCYMATERIAL_EMPTY_NAME.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(bean.getMaterialType())) {
                msg.setCode(BusinessCode.EMERGENCYMATERIAL_EMPTY_MATERIALTYPE.getCode());
                msg.setDescription(BusinessCode.EMERGENCYMATERIAL_EMPTY_MATERIALTYPE.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(bean.getCorpCode())) {
                msg.setCode(BusinessCode.EMERGENCYMATERIAL_EMPTY_CORP.getCode());
                msg.setDescription(BusinessCode.EMERGENCYMATERIAL_EMPTY_CORP.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(bean.getManager()) || StringUtils.isEmpty(bean.getManagerName())) {
                msg.setCode(BusinessCode.EMERGENCYMATERIAL_EMPTY_MANAGER.getCode());
                msg.setDescription(BusinessCode.EMERGENCYMATERIAL_EMPTY_MANAGER.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(bean.getCheckManager()) || StringUtils.isEmpty(bean.getCheckManagerName())) {
                msg.setCode(BusinessCode.EMERGENCYMATERIAL_EMPTY_CHECKMANAGER.getCode());
                msg.setDescription(BusinessCode.EMERGENCYMATERIAL_EMPTY_CHECKMANAGER.getDescription());
                return msg;
            }
            if (StringUtils.isNotEmpty(bean.getCode())) {
                //判断是否重复
                Integer count = factory.getMapper(EmergencyMaterialMapper.class).doubleByCode(bean.getCode(), bean.getId());
                if (count > 0) {
                    msg.setData(BusinessCode.EMERGENCYMATERIAL_DOUBLE_CODE.getCode());
                    msg.setDescription(BusinessCode.EMERGENCYMATERIAL_DOUBLE_CODE.getDescription());
                    return msg;
                }
            }
            if (null != files && files.length > 0) {
                for (MultipartFile file : files) {
                    String url = clientWrapper.uploadFile(file);
                    keepList.add(url + "#" + file.getOriginalFilename());
                    String pdfUrl = docConverterUtils.converterUpdate(file);
                    keepPdfList.add(StringUtils.isEmpty(pdfUrl) ? null : pdfUrl);
                }
            }
            Integer value = 0;
            if (StringUtils.isEmpty(bean.getId())) {
                //新增
                bean.setAddTime(bean.getUpdateTime());
                bean.setAddUser(bean.getUpdateUser());
                bean.setAddUserName(bean.getUpdateUserName());
                bean.setId(DefaultIdGenerator.getInstance().generateLongId());
                if (StringUtils.isEmpty(bean.getCode())) {
                    String code = generateCode(factory, bean.getCorpCode(), bean.getMaterialType());
                    Integer count = factory.getMapper(EmergencyMaterialMapper.class).doubleByCode(bean.getCode(), bean.getId());
                    if (count > 0) {
                        code = code + bean.getId();
                    }
                    bean.setCode(code);
                }
                if (null != keepList && keepList.size() > 0) {
                    bean.setAttachment(new Gson().toJson(keepList));
                }
                if (null != keepPdfList && keepPdfList.size() > 0) {
                    bean.setPreviewAttachment(new Gson().toJson(keepPdfList));
                }
                DictData data = factory.getMapper(DictDataMapper.class).queryOne(bean.getMaterialType());
                data.setReferenceCount(data.getReferenceCount() + 1);
                value = factory.getMapper(EmergencyMaterialMapper.class).insert(bean);
                factory.getMapper(DictDataMapper.class).update(data);
            } else {
                //修改
                EmergencyMaterial entity = queryOne(bean.getId()).getData();
                if (null == entity) {
                    msg.setData(BusinessCode.EMERGENCYMATERIAL_NOT_EXIST.getCode());
                    msg.setDescription(BusinessCode.EMERGENCYMATERIAL_NOT_EXIST.getDescription());
                    return msg;
                }
                if (StringUtils.isNotEmpty(keepFiles)) {
                    String[] keepArray = keepFiles.split("[,，]");
                    keepList.addAll(Arrays.asList(keepArray));
                }
                if (StringUtils.isNotEmpty(pdfKeepFiles)) {
                    String[] keepArray = pdfKeepFiles.split("[,，]");
                    keepPdfList.addAll(Arrays.asList(keepArray));
                }
                if (null != keepList && keepList.size() > 0) {
                    bean.setAttachment(new Gson().toJson(keepList));
                }
                if (null != keepPdfList && keepPdfList.size() > 0) {
                    bean.setPreviewAttachment(new Gson().toJson(keepPdfList));
                }
                List<DictData> dataList = new ArrayList<>();
                if (!StringUtils.equals(entity.getMaterialType(), bean.getMaterialType())) {
                    DictData data = factory.getMapper(DictDataMapper.class).queryOne(bean.getMaterialType());
                    if (null != data) {
                        data.setReferenceCount(data.getReferenceCount() + 1);
                        dataList.add(data);
                    }
                    DictData data1 = factory.getMapper(DictDataMapper.class).queryOne(entity.getMaterialType());
                    if (null != data1) {
                        data1.setReferenceCount(data1.getReferenceCount() - 1);
                        dataList.add(data1);
                    }
                }
                value = factory.getMapper(EmergencyMaterialMapper.class).update(bean);
                if (value > 0) {
                    if (StringUtils.isNotEmpty(delFiles)) {
                        String[] delArray = delFiles.split("[,，]");
                        for (String delUrl : delArray) {
                            clientWrapper.deleteFile(delUrl.split("#")[0]);
                        }
                    }
                    if (StringUtils.isNotEmpty(pdfDelFiles)) {
                        String[] delArray = pdfDelFiles.split("[,，]");
                        for (String delUrl : delArray) {
                            clientWrapper.deleteFile(delUrl.split("#")[0]);
                        }
                    }
                    if (null != dataList && dataList.size() > 0)
                        factory.getMapper(DictDataMapper.class).batchUpdate(dataList);
                }
            }
            msg.setData(value);
            if (value < 0) {
                if (null != keepPdfList && keepPdfList.size() > 0) {
                    if (StringUtils.isEmpty(pdfKeepFiles)) {
                        for (String url : keepPdfList) {
                            clientWrapper.deleteFile(url.split("#")[0]);
                        }
                    } else {
                        List<String> keeps = Arrays.asList(pdfKeepFiles.split("[,，]"));
                        for (String url : keepPdfList) {
                            if (!keeps.contains(url)) {
                                clientWrapper.deleteFile(url.split("#")[0]);
                            }
                        }
                    }
                }
                if (null != keepList && keepList.size() > 0) {
                    if (StringUtils.isEmpty(keepFiles)) {
                        for (String url : keepList) {
                            clientWrapper.deleteFile(url.split("#")[0]);
                        }
                    } else {
                        List<String> keeps = Arrays.asList(keepFiles.split("[,，]"));
                        for (String url : keepList) {
                            if (!keeps.contains(url)) {
                                clientWrapper.deleteFile(url.split("#")[0]);
                            }
                        }
                    }
                }
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("保存失败");
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            if (null != keepList && keepList.size() > 0) {
                if (StringUtils.isEmpty(keepFiles)) {
                    for (String url : keepList) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                } else {
                    List<String> keeps = Arrays.asList(keepFiles.split("[,，]"));
                    for (String url : keepList) {
                        if (!keeps.contains(url)) {
                            clientWrapper.deleteFile(url.split("#")[0]);
                        }
                    }
                }
            }
            if (null != keepPdfList && keepPdfList.size() > 0) {
                if (StringUtils.isEmpty(pdfKeepFiles)) {
                    for (String url : keepPdfList) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                } else {
                    List<String> keeps = Arrays.asList(pdfKeepFiles.split("[,，]"));
                    for (String url : keepPdfList) {
                        if (!keeps.contains(url)) {
                            clientWrapper.deleteFile(url.split("#")[0]);
                        }
                    }
                }
            }
            if (null != factory)
                factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }finally {
            if (null != factory){
                factory.close();
            }
        }
    }

    @Override
    public MessageBean<Integer> delete(String id) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "删除成功", Integer.class);
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.NOT_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.NOT_CHANGE_DATA.getDescription());
                return msg;
            }
            EmergencyMaterial entity = queryOne(id).getData();
            if (null == entity) {
                msg.setData(BusinessCode.EMERGENCYMATERIAL_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.EMERGENCYMATERIAL_NOT_EXIST.getDescription());
                return msg;
            }
            Integer value = factory.getMapper(EmergencyMaterialMapper.class).delete(id);
            msg.setData(value);
            if (value < 0) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("删除失败");
            } else {
                if (StringUtils.isNotEmpty(entity.getAttachment())) {
                    //删除文件
                    List<String> delFiles = JSONObject.parseArray(entity.getAttachment(), String.class);
                    if (null != delFiles && delFiles.size() > 0) {
                        for (String url : delFiles) {
                            clientWrapper.deleteFile(url.split("#")[0]);
                        }
                    }
                }
                if (StringUtils.isNotEmpty(entity.getPreviewAttachment())) {
                    //删除pdf文件
                    List<String> delFiles = JSONObject.parseArray(entity.getPreviewAttachment(), String.class);
                    if (null != delFiles && delFiles.size() > 0) {
                        for (String url : delFiles) {
                            clientWrapper.deleteFile(url.split("#")[0]);
                        }
                    }
                }
            }
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<EmergencyMaterial> queryOne(String id) {
        MessageBean<EmergencyMaterial> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "查询应急物资详情成功", EmergencyMaterial.class);
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.NOT_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.NOT_CHANGE_DATA.getDescription());
                return msg;
            }
            EmergencyMaterial entity = factory.getMapper(EmergencyMaterialMapper.class).queryOne(id);
            getNames(entity);
            List<MaterialCheckResultView> materialCheckResultViewList = factory.getMapper(EmergencyMaterialMapper.class).queryAssociatedCheck(entity.getId(), null, null);
            if (CollectionUtils.isNotEmpty(materialCheckResultViewList)) {
                Date lastCheckDate = materialCheckResultViewList.stream().map(MaterialCheckResultView::getCheckTime).max(Date::compareTo).get();
                entity.setLastCheckDate(lastCheckDate);
            }
            msg.setData(entity);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<DataBean<EmergencyMaterial>> list(String corpCode, String name, String materialType, Integer start, Integer rows,String keyword) {
        MessageBean<DataBean<EmergencyMaterial>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<EmergencyMaterial> list = factory.getMapper(EmergencyMaterialMapper.class).queryByCondition(corpCode, name, materialType, start, rows,keyword);
            Integer totalNumber = factory.getMapper(EmergencyMaterialMapper.class).countByCondition(corpCode, name, materialType,keyword);
            rows = rows == null ? totalNumber : (rows <= 0 ? 1 : rows);
            Integer totalPage = (totalNumber > rows) ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            DataBean<EmergencyMaterial> dataBean = new DataBean<>();
            list.forEach(item -> {
                getNames(item);
                List<MaterialCheckResultView> materialCheckResultViewList = factory.getMapper(EmergencyMaterialMapper.class).queryAssociatedCheck(item.getId(), null, null);
                if (CollectionUtils.isNotEmpty(materialCheckResultViewList)) {
                    Date lastCheckDate = materialCheckResultViewList.stream().map(MaterialCheckResultView::getCheckTime).max(Date::compareTo).get();
                    item.setLastCheckDate(lastCheckDate);
                }
            });
            dataBean.setList(list);
            dataBean.setTotalPage(totalPage);
            dataBean.setTotalNumber(totalNumber);
            dataBean.setPageSize(rows);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询应急物资列表成功");
            msg.setData(dataBean);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<?> MatrixToImage(String id) {
        MessageBean<Map> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "生成成功", Map.class);
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.NOT_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.NOT_CHANGE_DATA.getDescription());
                return msg;
            }
            EmergencyMaterial entity = queryOne(id).getData();
            if (null == entity) {
                msg.setCode(BusinessCode.EMERGENCYMATERIAL_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.EMERGENCYMATERIAL_NOT_EXIST.getDescription());
                return msg;
            }
            Map<String, Object> map = new HashMap<>();
            String name = "应急物资编号：" + entity.getCode() + ",应急物资名称：" + entity.getName() + "应急物资检查负责人：" +
                    entity.getCheckManagerName();
            String text = entity.getCode() + "#" + entity.getId();
            map.put("text", text);
            map.put("name", name);
            msg.setData(map);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<DataBean<MaterialCheckResultView>> queryCheckList(String materialId, Integer start, Integer rows) {
        MessageBean<DataBean<MaterialCheckResultView>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(materialId)) {
                msg.setCode(BusinessCode.EMPTY_PARAM.getCode());
                msg.setDescription(BusinessCode.EMPTY_PARAM.getDescription());
                return msg;
            }
            EmergencyMaterial entity = queryOne(materialId).getData();
            if (null == entity) {
                msg.setCode(BusinessCode.EMERGENCYMATERIAL_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.EMERGENCYMATERIAL_NOT_EXIST.getDescription());
                return msg;
            }
            List<MaterialCheckResultView> list = factory.getMapper(EmergencyMaterialMapper.class).queryAssociatedCheck(materialId, start, rows);
            if (list != null && list.size() > 0) {
                list.forEach(item -> item.setMaterialName(entity.getName()));
            }
            Integer totalNumber = factory.getMapper(EmergencyMaterialMapper.class).countAssociatedCheck(materialId);
            rows = rows == null ? totalNumber : (rows <= 0 ? 1 : rows);
            Integer totalPage = totalNumber > rows ? totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1 : 1;
            DataBean<MaterialCheckResultView> dataBean = new DataBean<>();
            dataBean.setList(list);
            dataBean.setTotalPage(totalPage);
            dataBean.setTotalNumber(totalNumber);
            dataBean.setPageSize(rows);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询检查记录列表");
            msg.setData(dataBean);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean importExcel(SessionFactory factory, StaffBean user, String corpCode, MultipartFile file) {
        MessageBean<String> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "导入成功", String.class);
        List<EmergencyMaterial> materialList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            InputStream inputStream = file.getInputStream();
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            XSSFSheet sheet = workbook.getSheetAt(0);
            if (sheet == null) {
                msg.setDescription(BusinessCode.FAILURE.getDescription());
                msg.setCode(BusinessCode.FAILURE.getCode());
                return msg;
            }
            // 获取excel表格行数
            int rows = sheet.getPhysicalNumberOfRows();
            // 从第二行开始读取数据
            for (int i = 2; i < rows; i++) {
                EmergencyMaterial material = new EmergencyMaterial();
                XSSFRow row = sheet.getRow(i);
                // 物质名称
                String name = getCellValue(row.getCell(0));
                // 编号
                String code = getCellValue(row.getCell(1));
                // 分类
                String materialTypeName = getCellValue(row.getCell(2));
                // 规格参数
                String materialParameter = getCellValue(row.getCell(3));
                // 单价
                String unitPrice = getCellValue(row.getCell(4));
                // 入库时间
                String storageTime = getCellValue(row.getCell(5));
                // 存储定额
                String reserveQuota = getCellValue(row.getCell(6));
                // 数量
                String existingQuantity = getCellValue(row.getCell(7));
                // 数量单位
                String quantityUnit = getCellValue(row.getCell(8));
                // 存放地点
                String place = getCellValue(row.getCell(9));
                // 状态
                String status = getCellValue(row.getCell(10));
                // 设备责任人
                String managerName = getCellValue(row.getCell(11));
                // 检查责任人
                String checkManagerName = getCellValue(row.getCell(12));

                if (!StringUtils.isEmpty(name)) {
                    material.setName(name);
                }
                if (!StringUtils.isEmpty(code)) {
                    material.setCode(code);
                }
                if (!StringUtils.isEmpty(materialTypeName)) {
                    material.setMaterialTypeName(materialTypeName);
                }
                if (!StringUtils.isEmpty(materialParameter)) {
                    material.setMaterialParameter(materialParameter);
                }
                if (!StringUtils.isEmpty(unitPrice)) {
                    material.setUnitPrice(Double.parseDouble(unitPrice));
                }
                if (!StringUtils.isEmpty(storageTime)) {
                    Date date = null;
                    try {
                        // 如果excel中为文本格式，切符合yyyy-MM-dd，直接转换成Date类型
                        date = sdf.parse(storageTime);
                    } catch (Exception e) {
                        logger.error(e.getMessage(),e);
                    } finally {
                        if (null == date) {
                            // 转换失败，默认excel中为日期格式
                            date = HSSFDateUtil.getJavaDate(Double.parseDouble(storageTime));
                        }
                    }
                    String expiredDate = null;
                    if (null != date) {
                        expiredDate = format.format(date);
                    }
                    if (null != expiredDate) {
                        // 由于Timestamp.valueOf(format)的值必须是yyyy-MM-dd HH:mm:ss 格式，提前转一次
                        material.setStorageTime(Timestamp.valueOf(expiredDate));
                    }
                }
                if (!StringUtils.isEmpty(reserveQuota)) {
                    material.setReserveQuota(Double.valueOf(reserveQuota).intValue());
                }
                if (!StringUtils.isEmpty(existingQuantity)) {
                    material.setExistingQuantity(Double.valueOf(existingQuantity).intValue());
                }
                if (!StringUtils.isEmpty(quantityUnit)) {
                    material.setQuantityUnit(quantityUnit);
                }
                if (!StringUtils.isEmpty(place)) {
                    material.setPlace(place);
                }
                if (!StringUtils.isEmpty(status)) {
                    material.setStatus(("正常").equals(status) ? 1 : ("异常").equals(status) ? 0 : null);
                }
                if (!StringUtils.isEmpty(managerName)) {
                    material.setManagerName(managerName);
                }
                if (!StringUtils.isEmpty(checkManagerName)) {
                    material.setCheckManagerName(checkManagerName);
                }
                if (!checkObjAllFieldsIsNull(material)) {
                    materialList.add(material);
                }
            }
            for (EmergencyMaterial material : materialList) {
                material.setCorpCode(corpCode);
                material.setId(DefaultIdGenerator.getInstance().generateLongId());
                material.setAddTime(new Date());
                material.setAddUser(user.getCode());
                material.setAddUserName(user.getName());
                material.setStatus(null == material.getStatus() ? 0 : material.getStatus());
                DictData dictData = dataService.matchDictData("应急物质类型", material.getMaterialTypeName());
                if (null != dictData) {
                    material.setMaterialType(dictData.getId());
                }
                // 根据检查负责人姓名查找人员信息
                if (StringUtils.isNotEmpty(material.getManagerName())) {
                    Map map = (Map) util.getStaffAndDeptFuzzyQuery(material.getManagerName().split("_")[0]).getData();
                    List<StaffBean> staffList = (List<StaffBean>) map.get("staffs");
                    if (null != staffList && staffList.size() > 0) {
                        material.setManager(staffList.get(0).getCode());
                    }
                }
                // 根据设备负责人姓名查找人员信息
                if (StringUtils.isNotEmpty(material.getCheckManagerName())) {
                    Map map1 = (Map) util.getStaffAndDeptFuzzyQuery(material.getCheckManagerName().split("_")[0]).getData();
                    List<StaffBean> staffBeanList = (List<StaffBean>) map1.get("staffs");
                    if (null != staffBeanList && staffBeanList.size() > 0) {
                        material.setCheckManager(staffBeanList.get(0).getCode());
                    }
                }
                if (StringUtils.isEmpty(material.getCode())) {
                    String code = generateCode(factory, material.getCorpCode(), material.getMaterialType());
                    Integer count = factory.getMapper(EmergencyMaterialMapper.class).doubleByCode(material.getCode(), material.getId());
                    if (count > 0) {
                        code = code + material.getId();
                    }
                    material.setCode(code);
                }
            }
            if (null != materialList && materialList.size() > 0) {
                Integer value = factory.getMapper(EmergencyMaterialMapper.class).batchInsert(materialList);
                if (value <= 0) {
                    factory.close(false);
                    msg.setCode(BusinessCode.FAILURE.getCode());
                    msg.setDescription(BusinessCode.FAILURE.getDescription());
                    return msg;
                }
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error(e.getMessage(),e);
            if (null != factory) {
                factory.close(false);
            }
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("导入失败");
            return msg;
        }
    }

    @Override
    public String generateCode(SessionFactory factory, String corpCode, String materialType) {
        StringBuilder code = new StringBuilder();
        CorpManagementMapper corpMapper = factory.getMapper(CorpManagementMapper.class);
        CorpBean corpBean = corpMapper.get(corpCode);
        if (corpBean == null) {
            code.append("#####");
        } else {
            code.append(corpBean.getShortCode());
        }
        if (StringUtils.isEmpty(code)) {
            code.append("#####");
        }
        DictData materialTypeData = factory.getMapper(DictDataMapper.class).queryOne(materialType);
        if (materialTypeData != null) {
            code.append(materialTypeData.getDictValue());
        }
        Integer count = factory.getMapper(EmergencyMaterialMapper.class).countByCondition(corpCode, null, materialType,null);
        NumberFormat nf = NumberFormat.getInstance();
        nf.setGroupingUsed(false);
        nf.setMaximumIntegerDigits(3); // 设置最大整数位数
        nf.setMinimumIntegerDigits(3); // 设置最小整数位数
        code.append(nf.format(count));
        return code.toString();
    }

    private void getNames(EmergencyMaterial bean) {
        if (bean != null) {
            Map<String, DictData> cacheMap = dataService.getCacheMap();
            if (StringUtils.isNotEmpty(bean.getMaterialType())) {
                DictData element = cacheMap.get(bean.getMaterialType());
                bean.setMaterialTypeName(element == null ? null : element.getDictLabel());
            }
        }
    }


    /**
     * 获取单元格的值
     *
     * @param cell
     * @return
     */
    @SuppressWarnings("deprecation")
    public static String getCellValue(XSSFCell cell) {
        if (cell == null) {
            return "";
        }
        if (cell.getCellTypeEnum() == CellType.STRING) {
            return cell.getStringCellValue();
        } else if (cell.getCellTypeEnum() == CellType.BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellTypeEnum() == CellType.FORMULA) {
            return cell.getCellFormula();
        } else if (cell.getCellTypeEnum() == CellType.NUMERIC) {
            return String.valueOf(cell.getNumericCellValue());
        } else {
            return "";
        }
    }


    /**
     * 判断对象及属性是否为空
     *
     * @param object
     * @return
     */
    public static boolean checkObjAllFieldsIsNull(Object object) {
        if (null == object) {
            return true;
        }
        try {
            for (Field f : object.getClass().getDeclaredFields()) {
                f.setAccessible(true);
                if (f.get(object) != null && StringUtils.isNotBlank(f.get(object).toString())) {
                    return false;
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return true;
    }
}
